package com.mxgraph.online;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mxgraph.utils.DateUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.logging.Logger;

public class UploadImageServlet extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    /**
     *
     */
    private static final Logger log = Logger
            .getLogger(SaveServlet.class.getName());

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadImageServlet()
    {
        super();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException
    {
        handlePost(request, response);
    }



    public static void handlePost(HttpServletRequest request,
                                  HttpServletResponse response) throws ServletException, IOException
    {
        if (request.getContentLength() < Constants.MAX_REQUEST_SIZE)
        {

            long t0 = System.currentTimeMillis();
            // Data in data param is base64 encoded and deflated
            String data = request.getParameterMap().get("data")[0];
            JSONObject jsonObject = JSON.parseObject(data);
            System.out.println(jsonObject.getString("filename"));
            System.out.println(URLDecoder.decode(jsonObject.getString("datas")));
            System.out.println(DateUtils.formatDate(jsonObject.getLong("createTime"),"yyyy-MM-dd HH:mm:ss"));
            System.out.println(DateUtils.formatDate(jsonObject.getLong("updateTime"),"yyyy-MM-dd HH:mm:ss"));

            try
            {
                response.setStatus(HttpServletResponse.SC_OK);
            }
            catch (OutOfMemoryError e)
            {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
            catch (IllegalArgumentException e)
            {
                log.warning("Error parsing xml contents : Original stack trace : " + e.getMessage());
            }finally {
                log.fine("save: ip=" + request.getRemoteAddr() +  " dt="
                        + (System.currentTimeMillis() - t0));
            }
        }
        else
        {
            response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        }
    }

}
